'use strict';

$(function() {
	
	var chat = new Chat(),
		$chatWindow = $('#chat-window'),
		$chatInput = $('#txt-message');
	
	$chatInput.bind('keyup', function(e) {
		
		console.info(e.which);
		
	});
	
	$chatInput.bind('keydown', function(e) {
		
		if (e.which === 13) {
			e.preventDefault();
			
			chat.send($chatInput.val());
		}
		
	});
	
	$('#btn-send').bind('click', function(e) {
		chat.send($chatInput.val());
	});
	
	chat.addEventListener(ChatEvent.MESSAGES_RECEIVED, function(e) {
		
	});
	
	function Chat() {
		
		this.listeners = { };
		this.lastMessageTimes = { };
		
		// Retrieve a list of the online users
		this.post('users', null, function(response) {
			
			// ..
			
		});
	}
	
	Chat.prototype.send = function(partnerId, message) {
		this.post('send', { partner: partnerId, message: message });
	}; 
	
	Chat.prototype.receive = function(partnerId) {
		
		if (!this.lastMessageTimes[partnerId]) {
			this.lastMessageTimes[partnerId] = Date.now();
		}
		
		var lastMessageTimestamp = this.lastMessageTimes[partnerId]; 
		
		this.post('receive', { partner: partnerId, lastMessageTimestamp: lastMessageTimestamp });
	};
	
	Chat.prototype.post = function(action, data, fn) {
		$.post(document.domain + '/chat/' + actopn, data, fn);
	};
	
	Chat.prototype.addEventListener = function(type, fn) {
		if (!this.listeners.hasOwnProperty(type)) {
			this.listeners[type] = [ ];
		}
		
		this.listeners[type].push(fn);
	};
	
	Chat.prototype.removeEventListener = function(type, fn) {
		if (!this.listeners.hasOwnProperty(type)) {
			return;
		}
		
		var index = this.listeners[type].indexOf(fn);
		
		if (index === -1)
			return;
		
		this.listeners[type].splice(index, 1);
	};
	
	function ChatEvent(target, type, data) {
		this.target = target;
		this.type = type;
		this.data = data;
	}
	
	ChatEvent.prototype.USER_LIST = 'userList';
	ChatEvent.prototype.USER_JOIN = 'userJoin';
	ChatEvent.prototype.USER_LEAVE = 'userLeave';
	
	ChatEvent.prototype.MESSAGES_RECEIVED = 'messagesReceived';
	
});